<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #menu_ids="{ model, field }">
        <BasicTree
          v-model:value="model[field]"
          :treeData="treeData"
          :fieldNames="{ title: 'menu_name', key: 'menu_id' }"
          checkable
          toolbar
          title="菜单分配"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './role.data';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { BasicTree, TreeItem } from '@/components/Tree';

  import { apiGetMenuTreeList } from '@/api/sys/menu';
  import { apiCreateRole, apiUpdateRole } from '@/api/sys/role';
  import { UpdateRoleReq } from '@/api/sys/model/role';

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const treeData = ref<TreeItem[]>([]);
  let menuCheck: { [key: number]: number } = {};
  const menuTypeMap = (menus: MenuTreeListItem[]): { [key: number]: number } => {
    let obj: { [key: number]: number } = {};
    menus.forEach((m) => {
      obj[m.menu_id] = m.menu_type;
      if (m.children && m.children.length > 0) {
        let _c = menuTypeMap(m.children);
        for (let k in _c) {
          obj[k] = _c[k];
        }
      }
    });
    return obj;
  };

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
    if (unref(treeData).length === 0) {
      let menuList = await apiGetMenuTreeList();
      treeData.value = menuList as any as TreeItem[];
      menuCheck = menuTypeMap(menuList);
      console.log(menuCheck);
    }
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'));

  async function handleSubmit() {
    try {
      const values = (await validate()) as UpdateRoleReq;
      setDrawerProps({ confirmLoading: true });
      // TODO custom api
      //updateRole  updateRole()
      values.role_id = parseInt(values.role_id);
      values.sort = parseInt(values.sort);
      if (values.menu_ids && values.menu_ids.length > 0) {
        let menuIds: number[] = [];
        values.menu_ids.forEach((v) => {
          if (menuCheck[v] == 2) {
            menuIds.push(v);
          }
        });
        values.menu_ids = menuIds;
      }

      if (unref(isUpdate)) {
        apiUpdateRole(values)
          .then(() => {
            closeDrawer();
            emit('success', '更新角色成功');
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        apiCreateRole(values)
          .then(() => {
            closeDrawer();
            emit('success', '添加角色成功');
          })
          .catch((err) => {
            console.log(err);
          });
      }
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
